/**
 * Created by zhong on 2018/1/25.
 */
let express = require( "express")
let mongoose = require( "mongoose")
let {tools} = require( "../../mixin/tools")
let Recipes = require( "../models/recipe.js")

const router = express.Router();
mongoose.Promise = global.Promise

router.post('/add',function (req,res) {
  let recipeInfo = req.body
  console.log(recipeInfo);
  if(!tools.check(0,recipeInfo.title)){
    res.json({ success:false,code:404,message: '请输入菜谱名称' })
    return
  }
  if(!tools.check(0,recipeInfo.desc)){
    res.json({ success:false,code:404,message: '请输入菜谱简介' })
    return
  }
  let recipe = new Recipes(recipeInfo)
  recipe.save(function (err,result) {
    if(err){
      console.log(err);
      res.json({ success:false,code:500,message: '添加失败' });
    }else{
      let data = {
        id:result._id
      }
      res.json({ success:true,code:0,message: '添加成功！',data:data })
    }
  })
})

router.put('/update',function (req,res) {
  let recipeInfo = req.body

  if(!tools.check(0,recipeInfo._id)){
    res.json({ success:false,code:404,message: '修改错误，没有找到该菜谱' })
    return
  }
  if(!tools.check(0,recipeInfo.title)){
    res.json({ success:false,code:404,message: '请输入菜谱标题' })
    return
  }
  if(!tools.check(0,recipeInfo.desc)){
    res.json({ success:false,code:404,message: '请输入菜谱简介' })
    return
  }
  Recipes.findOne({_id:recipeInfo._id},function (err,doc) {
    if(err) {
      console.log(err);
      return next(err)
    }
    if(doc){
      Recipes.update({_id:recipeInfo._id},recipeInfo,function (err,result) {
        if(err){
          // res.json({ success:false,code:0,message: err });
          console.log(err);
        }else{
          let data = {
            id:result._id
          }
          res.json({ success:true,code:0,message: '修改成功！',data:data })
        }
      })
    }else{
      res.json({ success:false,code:50013,message: '修改失败，请重新修改！' })
    }
  })
})

module.exports = router
